package com.xdl.modules.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xdl.common.response.ResponseCollection;
import com.xdl.common.response.ResponseResult;
import com.xdl.common.utils.StringUtils;
import com.xdl.configuration.BaseContextHandler;
import com.xdl.modules.system.entity.SysTenant;
import com.xdl.modules.system.model.BaseModel;
import com.xdl.modules.system.service.SysTenantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 多租户信息表 前端控制器
 * </p>
 *
 * @author iron guo
 * @since 2022-03-05
 */
@Slf4j
@RestController
@RequestMapping("/sys/tenant")
public class SysTenantController {

    @Autowired
    private SysTenantService tenantService;

    /**
     * 查询有效的 租户数据
     *
     * @return
     */
    @RequestMapping(value = "/queryList", method = RequestMethod.GET)
    public ResponseCollection<SysTenant> queryList(@RequestParam(name = "ids", required = false) String ids) {
        LambdaQueryWrapper<SysTenant> query = new LambdaQueryWrapper<>();
        query.eq(SysTenant::getStatus, 1);
        if (StringUtils.isNotEmpty(ids)) {
            query.in(SysTenant::getId, ids.split(","));
        }
        List<SysTenant> ls = tenantService.list(query);
        return ResponseCollection.Success(ls);
    }

    /**
     * 获取列表数据
     *
     * @return
     */
    @PostMapping("/list")
    public ResponseResult<IPage<SysTenant>> queryPageList(@RequestBody BaseModel model) {
        Page<SysTenant> page = new Page<SysTenant>(model.getPageNo(), model.getPageSize());
        IPage<SysTenant> pageList = tenantService.page(page);
        return ResponseResult.Success(pageList);
    }

    /**
     * 添加
     *
     * @param
     * @return
     */
    @PostMapping("/add")
    public ResponseResult<Boolean> add(@RequestBody SysTenant sysTenant) {
        Assert.isNull(tenantService.getById(sysTenant.getId()), "该编号已存在!");
        sysTenant.setCreateTime(new Date());
        sysTenant.setCreateBy(BaseContextHandler.getUsername());
        boolean save = tenantService.save(sysTenant);
        return ResponseResult.Success(save);
    }

    /**
     * 编辑
     *
     * @param
     * @return
     */
    @PutMapping("/edit")
    public ResponseResult<Boolean> edit(@RequestBody SysTenant tenant) {
        SysTenant sysTenant = tenantService.getById(tenant.getId());
        Assert.notNull(sysTenant, "未找到对应实体!");
        return ResponseResult.Success(tenantService.updateById(tenant));
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete", method = {RequestMethod.DELETE, RequestMethod.POST})
    public ResponseResult<?> delete(@RequestParam(name = "id", required = true) String id) {
        boolean remove = tenantService.removeTenantById(id);
        return ResponseResult.Success(remove);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public ResponseResult<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Assert.notNull(ids, "未选中租户！");
        String[] ls = ids.split(",");
        // 过滤掉已被引用的租户
        List<Integer> idList = new ArrayList<>();
        for (String id : ls) {
            int userCount = tenantService.countUserLinkTenant(id);
            if (userCount == 0) {
                idList.add(Integer.parseInt(id));
            }
        }
        if (idList.size() > 0) {
            tenantService.removeByIds(idList);
            if (ls.length == idList.size()) {
                return ResponseResult.Success("删除成功！");
            } else {
                return ResponseResult.Error("部分删除成功！（被引用的租户无法删除）！");
            }
        } else {
            return ResponseResult.Error("选择的租户都已被引用，无法删除！");
        }
    }

}
